/**
 * 注意: 目前只做了单文件上传
 */

import { uploadFiles } from '@/utils/mino';
import { Spin } from 'antd';
import Upload, { UploadFile } from 'antd/es/upload';
import { useEffect, useState } from 'react';
type UploadParam = {
  value?: string; //默认值
  onChange?: (url: string) => string; //设置参数
};
const MyFormUploadButton: React.FC<UploadParam> = (props) => {
  // Form.Item 默认传递进来的 value默认值,onChange修改表单值
  const { value, onChange } = props;
  // 上传中
  const [uploadLoading, setUploadLoading] = useState(false);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  useEffect(() => {
    if (value) {
      setFileList([
        {
          url: IMG_URL + value,
          uid: '',
          name: value,
        },
      ]);
    }
    return () => {
      setFileList([]);
    };
  }, []);

  return (
    <Upload
      fileList={fileList}
      maxCount={1}
      onRemove={() => {
        if (onChange) {
          onChange('');
        }
        setFileList([]);
      }}
      listType="picture-card"
      beforeUpload={async (file) => {
        setUploadLoading(true);
        try {
          // 先上传 后 设置值
          let res = await uploadFiles(file);
          if (onChange) {
            onChange(res);
          }
          // 上传有返回值 就设置列表回显,没有就置空
          if (res) {
            // 自定义缩略图
            setFileList([
              {
                url: IMG_URL + res,
                uid: file.uid,
                name: file.name,
              },
            ]);
          } else {
            setFileList([]);
          }
          setUploadLoading(false);
        } catch (error) {
          setUploadLoading(false);
        }
        return false;
      }}
    >
      {
        // delay 可以进行冻结,比如 一秒钟之内返回了,就不显示loading
        <Spin spinning={uploadLoading} tip="上传中...">
          点击上传
        </Spin>
      }
    </Upload>
  );
};

export default MyFormUploadButton;
